<template>
  <div class="payment-context-container">
    <div class="page-header">
      <h1>🔍 PaymentContext 展示</h1>
      <p>实时查看支付上下文构建过程和支付流程的详细信息</p>
      <div class="control-buttons">
        <button @click="refreshContext" class="refresh-btn">🔄 刷新</button>
        <button @click="clearLogs" class="clear-btn">🧹 清空日志</button>
        <button @click="exportLogs" class="export-btn">📤 导出日志</button>
      </div>
    </div>

    <!-- PaymentContext构建阶段 -->
    <div class="context-build-section">
      <h2>🔧 PaymentContext 构建流程</h2>
      <div class="build-steps">
        <div
          v-for="(step, index) in buildSteps"
          :key="step.id"
          class="build-step"
          :class="{
            completed: step.status === 'completed',
            processing: step.status === 'processing',
            error: step.status === 'error'
          }"
        >
          <div class="step-number">{{ index + 1 }}</div>
          <div class="step-content">
            <h4>{{ step.title }}</h4>
            <p>{{ step.description }}</p>
            <div v-if="step.data" class="step-data">
              <pre>{{ JSON.stringify(step.data, null, 2) }}</pre>
            </div>
            <div v-if="step.duration" class="step-timing">
              耗时: {{ step.duration }}ms
            </div>
          </div>
          <div class="step-status">
            <span class="status-icon">{{ getStatusIcon(step.status) }}</span>
          </div>
        </div>
      </div>
    </div>

    <!-- PaymentContext详情展示 -->
    <div v-if="paymentContext" class="context-detail-section">
      <h2>📋 PaymentContext 详情</h2>
      <div class="context-tabs">
        <button
          v-for="tab in contextTabs"
          :key="tab.key"
          class="tab-button"
          :class="{ active: activeTab === tab.key }"
          @click="activeTab = tab.key"
        >
          {{ tab.icon }} {{ tab.label }}
        </button>
      </div>

      <div class="context-content">
        <!-- 用户信息 -->
        <div v-if="activeTab === 'user'" class="context-panel">
          <h3>👤 用户信息</h3>
          <div class="info-grid">
            <div class="info-item">
              <span class="label">用户ID:</span>
              <span class="value">{{ paymentContext.userInfo.userId }}</span>
            </div>
            <div class="info-item">
              <span class="label">用户名:</span>
              <span class="value">{{ paymentContext.userInfo.userName }}</span>
            </div>
            <div class="info-item">
              <span class="label">用户类型:</span>
              <span class="value">{{ paymentContext.userInfo.userType }}</span>
            </div>
            <div class="info-item">
              <span class="label">设备平台:</span>
              <span class="value">{{ paymentContext.userInfo.deviceInfo.platform }}</span>
            </div>
            <div class="info-item">
              <span class="label">客户端IP:</span>
              <span class="value">{{ paymentContext.userInfo.deviceInfo.ip }}</span>
            </div>
            <div class="info-item full-width">
              <span class="label">User-Agent:</span>
              <span class="value">{{ paymentContext.userInfo.deviceInfo.userAgent }}</span>
            </div>
          </div>
        </div>

        <!-- 商户信息 -->
        <div v-if="activeTab === 'merchant'" class="context-panel">
          <h3>🏪 商户信息</h3>
          <div class="info-grid">
            <div class="info-item">
              <span class="label">商户ID:</span>
              <span class="value">{{ paymentContext.merchantInfo.merchantId }}</span>
            </div>
            <div class="info-item">
              <span class="label">商户名称:</span>
              <span class="value">{{ paymentContext.merchantInfo.merchantName }}</span>
            </div>
            <div class="info-item">
              <span class="label">商户类型:</span>
              <span class="value">{{ paymentContext.merchantInfo.merchantType }}</span>
            </div>
            <div class="info-item">
              <span class="label">业务类型:</span>
              <span class="value">{{ paymentContext.merchantInfo.businessType }}</span>
            </div>
            <div v-if="paymentContext.merchantInfo.serviceProvider" class="info-item">
              <span class="label">服务商:</span>
              <span class="value">{{ paymentContext.merchantInfo.serviceProvider }}</span>
            </div>
          </div>
        </div>

        <!-- 支付配置 -->
        <div v-if="activeTab === 'config'" class="context-panel">
          <h3>⚙️ 支付配置</h3>
          <div class="config-details">
            <div class="config-item">
              <h4>支付产品配置</h4>
              <div class="info-grid">
                <div class="info-item">
                  <span class="label">产品代码:</span>
                  <span class="value">{{ paymentContext.paymentConfig.productCode }}</span>
                </div>
                <div class="info-item">
                  <span class="label">支付渠道:</span>
                  <span class="value">{{ paymentContext.paymentConfig.channelId }}</span>
                </div>
                <div class="info-item">
                  <span class="label">费率:</span>
                  <span class="value">{{ paymentContext.paymentConfig.feeRate }}%</span>
                </div>
                <div class="info-item">
                  <span class="label">最小金额:</span>
                  <span class="value">￥{{ paymentContext.paymentConfig.minAmount }}</span>
                </div>
                <div class="info-item">
                  <span class="label">最大金额:</span>
                  <span class="value">￥{{ paymentContext.paymentConfig.maxAmount }}</span>
                </div>
              </div>
            </div>

            <div class="config-item">
              <h4>渠道参数</h4>
              <div class="config-params">
                <pre>{{ JSON.stringify(paymentContext.paymentConfig.channelParams, null, 2) }}</pre>
              </div>
            </div>
          </div>
        </div>

        <!-- 订单信息 -->
        <div v-if="activeTab === 'order'" class="context-panel">
          <h3>📦 订单信息</h3>
          <div class="info-grid">
            <div class="info-item">
              <span class="label">订单号:</span>
              <span class="value">{{ paymentContext.orderInfo.orderId }}</span>
            </div>
            <div class="info-item">
              <span class="label">支付金额:</span>
              <span class="value">￥{{ paymentContext.orderInfo.amount }}</span>
            </div>
            <div class="info-item">
              <span class="label">货币类型:</span>
              <span class="value">{{ paymentContext.orderInfo.currency }}</span>
            </div>
            <div class="info-item">
              <span class="label">商品名称:</span>
              <span class="value">{{ paymentContext.orderInfo.subject }}</span>
            </div>
            <div class="info-item">
              <span class="label">创建时间:</span>
              <span class="value">{{ paymentContext.orderInfo.createTime }}</span>
            </div>
            <div class="info-item">
              <span class="label">过期时间:</span>
              <span class="value">{{ paymentContext.orderInfo.expireTime }}</span>
            </div>
            <div class="info-item full-width">
              <span class="label">商品描述:</span>
              <span class="value">{{ paymentContext.orderInfo.body }}</span>
            </div>
          </div>
        </div>

        <!-- 请求参数 -->
        <div v-if="activeTab === 'request'" class="context-panel">
          <h3>📤 请求参数</h3>
          <div class="request-details">
            <h4>原始请求参数</h4>
            <pre class="code-block">{{ JSON.stringify(paymentContext.originalRequest, null, 2) }}</pre>

            <h4>渠道请求参数</h4>
            <pre class="code-block">{{ JSON.stringify(paymentContext.channelRequest, null, 2) }}</pre>
          </div>
        </div>

        <!-- 响应信息 -->
        <div v-if="activeTab === 'response'" class="context-panel">
          <h3>📥 响应信息</h3>
          <div class="response-details">
            <div v-if="paymentContext.channelResponse" class="response-item">
              <h4>渠道响应</h4>
              <pre class="code-block">{{ JSON.stringify(paymentContext.channelResponse, null, 2) }}</pre>
            </div>

            <div v-if="paymentContext.finalResponse" class="response-item">
              <h4>最终响应</h4>
              <pre class="code-block">{{ JSON.stringify(paymentContext.finalResponse, null, 2) }}</pre>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 实时日志流 -->
    <div class="logs-stream-section">
      <h2>📝 实时处理日志</h2>
      <div class="logs-controls">
        <div class="log-filters">
          <button
            v-for="level in logLevels"
            :key="level"
            class="filter-btn"
            :class="{ active: activeLogLevels.includes(level) }"
            @click="toggleLogLevel(level)"
          >
            {{ level.toUpperCase() }}
          </button>
        </div>
        <div class="log-stats">
          <span>总计: {{ filteredLogs.length }} 条</span>
          <span>错误: {{ errorLogCount }} 条</span>
          <span>警告: {{ warningLogCount }} 条</span>
        </div>
      </div>

      <div class="logs-stream" ref="logsContainer">
        <div
          v-for="(log, index) in filteredLogs"
          :key="index"
          class="log-entry"
          :class="`log-${log.level}`"
        >
          <span class="log-timestamp">{{ log.timestamp }}</span>
          <span class="log-level-badge">{{ log.level.toUpperCase() }}</span>
          <span class="log-source">{{ log.source }}</span>
          <span class="log-message">{{ log.message }}</span>
          <div v-if="log.data" class="log-data">
            <pre>{{ JSON.stringify(log.data, null, 2) }}</pre>
          </div>
        </div>
      </div>
    </div>

    <!-- 性能指标 -->
    <div class="performance-section">
      <h2>⚡ 性能指标</h2>
      <div class="metrics-grid">
        <div class="metric-card">
          <div class="metric-value">{{ performanceMetrics.totalDuration }}ms</div>
          <div class="metric-label">总耗时</div>
        </div>
        <div class="metric-card">
          <div class="metric-value">{{ performanceMetrics.contextBuildTime }}ms</div>
          <div class="metric-label">Context构建</div>
        </div>
        <div class="metric-card">
          <div class="metric-value">{{ performanceMetrics.paymentCallTime }}ms</div>
          <div class="metric-label">支付调用</div>
        </div>
        <div class="metric-card">
          <div class="metric-value">{{ performanceMetrics.channelResponseTime }}ms</div>
          <div class="metric-label">渠道响应</div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, nextTick } from 'vue'

// 接口定义
interface BuildStep {
  id: string
  title: string
  description: string
  status: 'pending' | 'processing' | 'completed' | 'error'
  data?: any
  duration?: number
}

interface PaymentContext {
  userInfo: {
    userId: string
    userName: string
    userType: string
    deviceInfo: {
      platform: string
      userAgent: string
      ip: string
    }
  }
  merchantInfo: {
    merchantId: string
    merchantName: string
    merchantType: string
    businessType: string
    serviceProvider?: string
  }
  paymentConfig: {
    productCode: string
    channelId: string
    feeRate: number
    minAmount: number
    maxAmount: number
    channelParams: any
  }
  orderInfo: {
    orderId: string
    amount: number
    currency: string
    subject: string
    body: string
    createTime: string
    expireTime: string
  }
  originalRequest: any
  channelRequest: any
  channelResponse?: any
  finalResponse?: any
}

interface LogEntry {
  timestamp: string
  level: 'info' | 'warn' | 'error' | 'debug'
  source: string
  message: string
  data?: any
}

interface PerformanceMetrics {
  totalDuration: number
  contextBuildTime: number
  paymentCallTime: number
  channelResponseTime: number
}

// 响应式数据
const activeTab = ref('user')
const buildSteps = ref<BuildStep[]>([])
const paymentContext = ref<PaymentContext | null>(null)
const logs = ref<LogEntry[]>([])
const activeLogLevels = ref(['info', 'warn', 'error', 'debug'])
const performanceMetrics = ref<PerformanceMetrics>({
  totalDuration: 0,
  contextBuildTime: 0,
  paymentCallTime: 0,
  channelResponseTime: 0
})
const logsContainer = ref<HTMLElement>()

// 常量
const logLevels = ['info', 'warn', 'error', 'debug']

const contextTabs = [
  { key: 'user', label: '用户信息', icon: '👤' },
  { key: 'merchant', label: '商户信息', icon: '🏪' },
  { key: 'config', label: '支付配置', icon: '⚙️' },
  { key: 'order', label: '订单信息', icon: '📦' },
  { key: 'request', label: '请求参数', icon: '📤' },
  { key: 'response', label: '响应信息', icon: '📥' }
]

// 计算属性
const filteredLogs = computed(() => {
  return logs.value.filter(log => activeLogLevels.value.includes(log.level))
})

const errorLogCount = computed(() => {
  return logs.value.filter(log => log.level === 'error').length
})

const warningLogCount = computed(() => {
  return logs.value.filter(log => log.level === 'warn').length
})

// 方法
const getStatusIcon = (status: string) => {
  switch (status) {
    case 'completed': return '✅'
    case 'processing': return '⏳'
    case 'error': return '❌'
    default: return '⏸️'
  }
}

const toggleLogLevel = (level: string) => {
  const index = activeLogLevels.value.indexOf(level)
  if (index > -1) {
    activeLogLevels.value.splice(index, 1)
  } else {
    activeLogLevels.value.push(level)
  }
}

const refreshContext = () => {
  // 刷新PaymentContext数据
  loadMockData()
}

const clearLogs = () => {
  logs.value = []
}

const exportLogs = () => {
  const logData = JSON.stringify(logs.value, null, 2)
  const blob = new Blob([logData], { type: 'application/json' })
  const url = URL.createObjectURL(blob)
  const a = document.createElement('a')
  a.href = url
  a.download = `payment-logs-${new Date().toISOString()}.json`
  a.click()
  URL.revokeObjectURL(url)
}

const addLog = (level: LogEntry['level'], source: string, message: string, data?: any) => {
  logs.value.push({
    timestamp: new Date().toLocaleTimeString(),
    level,
    source,
    message,
    data
  })

  // 自动滚动到底部
  nextTick(() => {
    if (logsContainer.value) {
      logsContainer.value.scrollTop = logsContainer.value.scrollHeight
    }
  })
}

const loadMockData = () => {
  // 模拟构建步骤
  buildSteps.value = [
    {
      id: 'validate-request',
      title: '请求参数验证',
      description: '验证支付请求的必要参数',
      status: 'completed',
      duration: 15
    },
    {
      id: 'load-user',
      title: '加载用户信息',
      description: '从数据库获取用户基本信息和设备信息',
      status: 'completed',
      duration: 45
    },
    {
      id: 'load-merchant',
      title: '加载商户信息',
      description: '获取商户配置和业务信息',
      status: 'completed',
      duration: 32
    },
    {
      id: 'resolve-config',
      title: '解析支付配置',
      description: '根据商户和产品类型解析支付配置',
      status: 'completed',
      duration: 78
    },
    {
      id: 'build-context',
      title: '构建PaymentContext',
      description: '将所有信息组装为PaymentContext对象',
      status: 'completed',
      duration: 23
    }
  ]

  // 模拟PaymentContext数据
  paymentContext.value = {
    userInfo: {
      userId: 'user_001',
      userName: '生辉',
      userType: '企业用户',
      deviceInfo: {
        platform: 'iOS',
        userAgent: 'Mozilla/5.0 (iPhone; CPU iPhone OS 16_0 like Mac OS X)',
        ip: '192.168.1.100'
      }
    },
    merchantInfo: {
      merchantId: 'merch_001',
      merchantName: '全家便利店',
      merchantType: '特约商户',
      businessType: '便利店零售',
      serviceProvider: '上海火金网络科技有限公司'
    },
    paymentConfig: {
      productCode: 'WX_JSAPI',
      channelId: 'WECHAT',
      feeRate: 0.6,
      minAmount: 0.01,
      maxAmount: 50000,
      channelParams: {
        appId: 'wx1234567890abcdef',
        mchId: '1230000000',
        apiKey: '***hidden***',
        notifyUrl: 'https://api.anypay.com/notify/wechat'
      }
    },
    orderInfo: {
      orderId: 'ORDER_' + Date.now(),
      amount: 1.0,
      currency: 'CNY',
      subject: '测试商品',
      body: '这是一个支付测试商品',
      createTime: new Date().toLocaleString(),
      expireTime: new Date(Date.now() + 30 * 60 * 1000).toLocaleString()
    },
    originalRequest: {
      userId: 'user_001',
      merchantId: 'merch_001',
      productCode: 'WX_JSAPI',
      amount: 1.0,
      subject: '测试商品'
    },
    channelRequest: {
      appid: 'wx1234567890abcdef',
      mch_id: '1230000000',
      out_trade_no: 'ORDER_' + Date.now(),
      body: '测试商品',
      total_fee: 100,
      spbill_create_ip: '192.168.1.100',
      notify_url: 'https://api.anypay.com/notify/wechat',
      trade_type: 'JSAPI'
    }
  }

  // 模拟性能指标
  performanceMetrics.value = {
    totalDuration: 2143,
    contextBuildTime: 193,
    paymentCallTime: 1256,
    channelResponseTime: 694
  }

  // 添加初始日志
  addLog('info', 'PaymentContext', 'PaymentContext构建完成')
  addLog('debug', 'UserService', '用户信息加载成功', { userId: 'user_001' })
  addLog('debug', 'MerchantService', '商户信息加载成功', { merchantId: 'merch_001' })
  addLog('info', 'ConfigService', '支付配置解析完成')
}

onMounted(() => {
  loadMockData()
})
</script>

<style scoped>
.payment-context-container {
  padding: 24px;
  max-width: 1400px;
  margin: 0 auto;
}

.page-header {
  margin-bottom: 32px;
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
}

.page-header h1 {
  font-size: 28px;
  font-weight: 600;
  color: #1a1a1a;
  margin: 0 0 8px 0;
}

.page-header p {
  color: #666;
  font-size: 16px;
  margin: 0;
}

.control-buttons {
  display: flex;
  gap: 12px;
}

.control-buttons button {
  padding: 8px 16px;
  border: 1px solid #d9d9d9;
  border-radius: 6px;
  background: white;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.3s ease;
}

.control-buttons button:hover {
  border-color: #1890ff;
  color: #1890ff;
}

/* 构建步骤样式 */
.context-build-section {
  margin-bottom: 32px;
}

.build-steps {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.build-step {
  display: flex;
  align-items: flex-start;
  gap: 16px;
  background: white;
  border: 1px solid #e8e8e8;
  border-radius: 12px;
  padding: 20px;
  transition: all 0.3s ease;
}

.build-step.completed {
  border-color: #52c41a;
  background: #f6ffed;
}

.build-step.processing {
  border-color: #1890ff;
  background: #f0f9ff;
}

.build-step.error {
  border-color: #ff4d4f;
  background: #fff2f0;
}

.step-number {
  width: 32px;
  height: 32px;
  border-radius: 50%;
  background: #f0f0f0;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: 600;
  flex-shrink: 0;
}

.build-step.completed .step-number {
  background: #52c41a;
  color: white;
}

.step-content {
  flex: 1;
}

.step-content h4 {
  margin: 0 0 8px 0;
  font-size: 16px;
  font-weight: 600;
  color: #1a1a1a;
}

.step-content p {
  margin: 0 0 12px 0;
  color: #666;
  line-height: 1.4;
}

.step-data {
  background: #f8f9fa;
  border-radius: 6px;
  padding: 12px;
  margin: 8px 0;
  overflow-x: auto;
}

.step-data pre {
  margin: 0;
  font-size: 12px;
  color: #333;
}

.step-timing {
  font-size: 12px;
  color: #666;
  font-weight: 500;
}

.step-status {
  font-size: 20px;
}

/* Context详情样式 */
.context-detail-section {
  margin-bottom: 32px;
}

.context-tabs {
  display: flex;
  border-bottom: 1px solid #e8e8e8;
  margin-bottom: 24px;
}

.tab-button {
  padding: 12px 24px;
  border: none;
  background: none;
  cursor: pointer;
  font-size: 14px;
  font-weight: 500;
  color: #666;
  border-bottom: 2px solid transparent;
  transition: all 0.3s ease;
}

.tab-button.active {
  color: #1890ff;
  border-bottom-color: #1890ff;
}

.tab-button:hover {
  color: #1890ff;
}

.context-panel {
  background: white;
  border: 1px solid #e8e8e8;
  border-radius: 12px;
  padding: 24px;
}

.info-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 16px;
}

.info-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 0;
  border-bottom: 1px solid #f0f0f0;
}

.info-item.full-width {
  grid-column: 1 / -1;
}

.info-item:last-child {
  border-bottom: none;
}

.info-item .label {
  font-weight: 500;
  color: #666;
  width: 120px;
  flex-shrink: 0;
}

.info-item .value {
  font-weight: 500;
  color: #1a1a1a;
  text-align: right;
  word-break: break-all;
}

.code-block {
  background: #f8f9fa;
  border-radius: 6px;
  padding: 16px;
  margin: 12px 0;
  overflow-x: auto;
  font-size: 12px;
  line-height: 1.4;
}

/* 日志流样式 */
.logs-stream-section {
  margin-bottom: 32px;
}

.logs-controls {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.log-filters {
  display: flex;
  gap: 8px;
}

.filter-btn {
  padding: 6px 12px;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
  background: white;
  cursor: pointer;
  font-size: 12px;
  font-weight: 500;
  transition: all 0.3s ease;
}

.filter-btn.active {
  background: #1890ff;
  color: white;
  border-color: #1890ff;
}

.log-stats {
  display: flex;
  gap: 16px;
  font-size: 14px;
  color: #666;
}

.logs-stream {
  background: #1f1f1f;
  border-radius: 12px;
  padding: 16px;
  max-height: 400px;
  overflow-y: auto;
  font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
}

.log-entry {
  display: flex;
  align-items: flex-start;
  gap: 12px;
  padding: 6px 0;
  font-size: 12px;
  line-height: 1.4;
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
}

.log-entry:last-child {
  border-bottom: none;
}

.log-timestamp {
  color: #888;
  width: 80px;
  flex-shrink: 0;
}

.log-level-badge {
  width: 50px;
  flex-shrink: 0;
  font-weight: 600;
}

.log-info .log-level-badge {
  color: #52c41a;
}

.log-warn .log-level-badge {
  color: #faad14;
}

.log-error .log-level-badge {
  color: #ff4d4f;
}

.log-debug .log-level-badge {
  color: #1890ff;
}

.log-source {
  color: #40a9ff;
  width: 120px;
  flex-shrink: 0;
}

.log-message {
  color: #d9d9d9;
  flex: 1;
}

.log-data {
  margin-top: 8px;
  background: rgba(255, 255, 255, 0.05);
  border-radius: 4px;
  padding: 8px;
  grid-column: 1 / -1;
}

.log-data pre {
  margin: 0;
  color: #d9d9d9;
  font-size: 11px;
}

/* 性能指标样式 */
.performance-section h2 {
  font-size: 22px;
  font-weight: 600;
  color: #1a1a1a;
  margin-bottom: 16px;
}

.metrics-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 16px;
}

.metric-card {
  background: white;
  border: 1px solid #e8e8e8;
  border-radius: 12px;
  padding: 24px;
  text-align: center;
}

.metric-value {
  font-size: 32px;
  font-weight: 700;
  color: #1890ff;
  margin-bottom: 8px;
}

.metric-label {
  font-size: 14px;
  color: #666;
  font-weight: 500;
}
</style>